<!-- Edit Time Entry -->
<!-- Author: Edwin -->
<template>
  <el-dialog :visible.sync="editTimeEntryDialog"
             @closed='closeAfterDialog'
             class="cui-custom-css"
             width="470px"
             :close-on-click-modal="false"
             append-to-body>
    <div slot="title"
         style="fontSize:18px;textAlign:left;">
      <template v-if="dialogType === 'record' && isApprove">{{ $t('custom.attendance.timeEntry.approveTitle') }}</template>
      <template v-else>{{ $t('custom.attendance.timeEntry.editTitle') }}</template>
    </div>
    <div>
      <div v-if="!isApprove"
           style="height:40px;background:#E6F7FF;border-radius: 2px;display: flex;align-items: center;">
        <span v-if="dialogType === 'record' && !isApprove"
              style="color: #138DC7;font-weight: 400; margin-left:10px;">{{ $t('custom.attendance.timeEntry.modifyTips') }}</span>
        <span v-else
              style="color: #138DC7;font-weight: 400; margin-left:10px;">{{ $t('custom.attendance.timeEntry.editTips') }}</span>
      </div>
      <div :style="{'padding-top':isApprove?0:'20px','padding-bottom':'10px','display':'flex','justify-content': 'flex-start','align-items': 'flex-end'}">
        <!-- action -->
        <div style="width: 130px;height: 75px;background: #F5F7FA;border-radius: 2px;">
          <div style="width: 46px;padding-top: 8px;margin-left: 10px;height: 17px;font-size: 12px;font-weight: 600;color: #BEBEBE;line-height: 17px;">{{$t('custom.attendance.timeEntry.action')}}</div>
          <div style="display: flex;padding: 8px;padding-top:10px">
            <div v-if="userStatus === 'IN'"
                 style="background:#67C23A;width: 10px;height: 10px;margin:8px 6px 8px 6px;border-radius:5px;"></div>
            <div v-else-if="userStatus === 'BACK'"
                 style="background:#909399;width: 10px;height: 10px;margin:8px 6px 8px 6px;border-radius:5px;"></div>
            <div v-else-if="userStatus === 'OUT'"
                 style="background:#F56C6C;width: 10px;height: 10px;margin:8px 6px 8px 6px;border-radius:5px;"></div>
            <div v-else-if="userStatus === 'BREAK'"
                 style="background:#138DC7;width: 10px;height: 10px;margin:8px 6px 8px 6px;border-radius:5px;"></div>
            <div v-else-if="userStatus === 'LUNCH'"
                 style="background:#138DC7;width: 10px;height: 10px;margin:8px 6px 8px 6px;border-radius:5px;"></div>
            <span style="height: 26px;font-size: 18px;font-weight: 600;color: #404040;line-height: 26px;">{{ userStatus }}</span>
          </div>
        </div>
        <!-- time -->
        <div style="width: 130px;height: 75px;background: #F5F7FA;border-radius: 2px;margin-left:20px;">
          <div style="width: 130px;height: 75px;background: #F5F7FA;border-radius: 2px;padding-left:10px">
            <div style="text-align:left;padding-top:8px;height: 17px;font-size: 12px;font-weight: 600;color: #BEBEBE;line-height: 17px;">{{isApprove?$t('custom.attendance.timeEntry.originaltime'):$t('custom.attendance.timeEntry.time')}}</div>
            <div style="display: flex;padding-top:8px;flex-direction: column;text-align: left;">
              <span style="width: 100px;height: 25px;font-size: 18px;font-weight: 600;color: #404040;line-height: 25px;">{{timestampTimeView}}</span>
              <span style="width: 100px;height: 17px;font-size: 12px;font-weight: 400;color: #7F7F7F;line-height: 17px;">{{timestampDateView}} {{timestampTimeZoneView}}</span>
            </div>
          </div>
        </div>
        <!-- time -->
        <div v-if="isApprove"
             style="width: 130px;height: 75px;background: #F5F7FA;border-radius: 2px;margin-left:20px;">
          <div style="width: 130px;height: 75px;background: #F5F7FA;border-radius: 2px;padding-left:10px">
            <div style="text-align:left;padding-top:8px;height: 17px;font-size: 12px;font-weight: 600;color: #BEBEBE;line-height: 17px;">{{$t('custom.attendance.timeEntry.adjusttime')}}</div>
            <div style="display: flex;padding-top:8px;flex-direction: column;text-align: left;">
              <span style="width: 100px;height: 25px;font-size: 18px;font-weight: 600;color: #404040;line-height: 25px;">{{adjusttimestampTimeView}}</span>
              <span style="width: 100px;height: 17px;font-size: 12px;font-weight: 400;color: #7F7F7F;line-height: 17px;">{{adjusttimestampDateView}} {{adjusttimestampTimeZoneView}}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isApprove"
           style="margin:10px 0;display:flex;align-items:center">
        <div style="width:28px;height:28px;border-radius:50%;backgroundColor:#138DC7;color:#fff;line-height:28px">{{username | usernameFilter}}</div>&nbsp;&nbsp;
        <span style="color:#404040;font-size:14px;font-weight: 500;">{{username}}</span>&nbsp;&nbsp;
        <span style="color:#7F7F7F">submit application -</span>&nbsp;
        <span style="color:#7F7F7F">{{timestampDateView}} {{timestampTimeView}} {{timestampTimeZoneView}}</span>
      </div>
      <el-form label-width="120px"
               label-position="top">
        <el-form-item v-if="!isApprove"
                      :label="$t('custom.attendance.timeEntry.adjustto')"
                      style="textAlign:left;">
          <!-- <el-date-picker v-model="timestamp"
                          :disabled="isApprove"
                          type="datetime"
                          placeholder="Select Timestamp">
          </el-date-picker> -->
          <el-date-picker style="width: 205px;border-radius: 4px;border: 1px solid #D8DCE6;"
                          v-model="timestampDateData"
                          type="date"
                          :placeholder="$t('custom.attendance.timeEntry.selectdate')">
          </el-date-picker>
          <el-time-select style="width: 205px;border-radius: 4px;border: 1px solid #D8DCE6;margin-left:20px;"
                          v-model="timestampTimeData"
                          :picker-options="{
              start: '00:00',
              step: '00:10',
              end: '23:59'
            }"
                          :placeholder="$t('custom.attendance.timeEntry.selecttime')">
          </el-time-select>
        </el-form-item>
        <!-- <el-form-item label="Action"
                      style="color:#aaa;textAlign:left;">{{ userStatus }}</el-form-item>
        <el-form-item label="Timestamp"
                      style="textAlign:left;">
          <el-date-picker v-model="timestamp"
                          :disabled="isApprove"
                          type="datetime"
                          placeholder="Select Timestamp">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item :label="isApprove?'':$t('custom.attendance.timeEntry.comment')"
                      style="textAlign:left;">
          <el-input type="textarea"
                    resize="none"
                    v-model="comments"
                    :disabled="isApprove"
                    placeholder="State your reason for filing an application to adjust your check-in time."></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <!-- <el-button size="small"
                 @click="closeDialog">{{ $t('custom.attendance.timeEntry.cancelBtn') }}</el-button> -->
      <template v-if="isApprove">
        <el-button size="small"
                   type="danger"
                   style="#138DC7"
                   :loading="loadingDeclineBtn"
                   @click="declineEdit">{{ $t('custom.attendance.timeEntry.rejectBtn') }}</el-button>
        <el-button size="small"
                   type="primary"
                   :loading="loadingApproveBtn"
                   @click="approveEdit">{{ $t('custom.attendance.timeEntry.approveBtn') }}</el-button>
      </template>
      <template v-else>
        <el-button size="small"
                   type="primary"
                   :loading="loadingSaveBtn"
                   @click="saveEdit">{{ dialogType === 'record'?$t('custom.attendance.timeEntry.recordsaveBtn'):$t('custom.attendance.timeEntry.saveBtn') }}</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'
import thisStore from '@/store'
import i18n from '@/i18n'
import { GlobalTimeformat } from '@/utils/common'
export default {
  props: {
    itemInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: null
    },
    isApprove: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      editTimeEntryDialog: false,
      loadingSaveBtn: false,
      loadingDeclineBtn: false,
      loadingApproveBtn: false,
      userStatus: null,
      timestamp: null,
      comments: null,
      timestampDateView: null,
      timestampTimeView: null,
      timestampTimeZoneView: null,
      adjusttimestampDateView: null,
      adjusttimestampTimeView: null,
      adjusttimestampTimeZoneView: null,
      timestampDateData: null,
      timestampTimeData: null,
      username: null
    }
  },
  watch: {
    editTimeEntryDialog (e) {
      if (e) {
        // let pattern = store.state.user.timeFormat ? store.state.user.timeFormat : 'MM/DD/YYYY'
        // moment.tz(time, store.state.user.timezoneId).format(pattern + ' ' + (last || '')) + ' ' + store.state.user.timezoneName
        if (this.dialogType === 'record') {
          this.timestamp = GlobalTimeformat(this.itemInfo.logTime, 'HH:mm:ss') // moment.tz(this.itemInfo.logTime, thisStore.state.user.timezoneId).format('YYYY-MM-DD HH:mm:ss')
          this.adjusttimestamp = GlobalTimeformat(this.itemInfo.logTimeUpdated, 'HH:mm:ss') // moment.tz(this.itemInfo.logTime, thisStore.state.user.timezoneId).format('YYYY-MM-DD HH:mm:ss')
        } else {
          this.timestamp = GlobalTimeformat(this.itemInfo.logTime, 'HH:mm:ss') // moment.tz(this.itemInfo.logTime, this.itemInfo.timezone).format('YYYY-MM-DD HH:mm:ss')
          this.adjusttimestamp = GlobalTimeformat(this.itemInfo.logTimeUpdated, 'HH:mm:ss') // moment.tz(this.itemInfo.logTime, this.itemInfo.timezone).format('YYYY-MM-DD HH:mm:ss')
        }
        if (this.itemInfo.subAction) {
          this.userStatus = this.itemInfo.subAction.toUpperCase()
        } else {
          this.userStatus = this.itemInfo.action.toUpperCase()
        }
        if (this.dialogType === 'record') {
          this.comments = this.itemInfo.comments
        } else {
          this.comments = null
        }
        this.timestampDateView = this.timestamp.split(' ')[0]
        this.timestampTimeView = this.timestamp.split(' ')[1]
        this.timestampTimeZoneView = this.timestamp.split(' ')[2]
        this.adjusttimestampDateView = this.adjusttimestamp.split(' ')[0]
        this.adjusttimestampTimeView = this.adjusttimestamp.split(' ')[1]
        this.adjusttimestampTimeZoneView = this.adjusttimestamp.split(' ')[2]
        this.username = this.itemInfo.username
      } else {
        this.comments = null
      }
    }
  },
  computed:{
    nowUserId () {
      return thisStore.state.user.id
    },
  },
  filters: {
    usernameFilter (val) {
      if (val) {
        val = val.split(' ')[0][0] + val.split(' ')[1][0]
      }
      return val
    }
  },
  methods: {
    declineEdit () {
      this.loadingDeclineBtn = true
      const params = {
        approveUserId: this.itemInfo.userId,
        id: this.itemInfo.approveId,
        dataContent: [],
        status: 'Decline'
      }
      this.$interface.attendance.approveTimeEntryApi(params)
        .then(({ data: res }) => {
          this.loadingDeclineBtn = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
            this.closeDialog()
            this.$emit('initOther')
          }
        })
        .catch(() => {
          this.loadingDeclineBtn = false
        })
    },
    approveEdit () {
      this.loadingApproveBtn = true
      let tempArr=Array.isArray(this.itemInfo.dataContent)?this.itemInfo.dataContent:[]
      let approversList=Array.isArray(this.itemInfo.column.dict.approvers)?this.itemInfo.column.dict.approvers:[]
      if (this.itemInfo.column.dict.all === 'all' && !(!this.itemInfo.managerUserId && this.itemInfo.column.dict.approvers.includes('0000000000'))&&tempArr.length<approversList.length-1) {
        const params = {
          id: this.itemInfo.approveId,
          dataContent: [...tempArr,this.nowUserId]
        }
        this.$interface.attendance.approveTimeEntryApi(params)
          .then(({ data: res }) => {
            this.loadingApproveBtn = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            if (res.data) {
              this.$message.success(res.msg)
              this.closeDialog()
              this.$emit('initOther')
            }
          })
          .catch(() => {
            this.loadingApproveBtn = false
          })
      } else {
        const params = {
          dataContent: [],
          id: this.itemInfo.approveId,
          status: 'Approved'
        }
        this.$interface.attendance.approveTimeEntryApi(params)
          .then(({ data: res }) => {
            this.loadingApproveBtn = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            if (res.data) {
              this.$message.success(res.msg)
              this.closeDialog()
              this.$emit('initOther')
            }
          })
          .catch(() => {
            this.loadingApproveBtn = false
          })
      }
    },
    saveEdit () {
      this.loadingSaveBtn = true
      const _self = this
      if (!_self.timestampDateData || !_self.timestampTimeData) {
        this.loadingSaveBtn = false
        return _self.$message.error('Please select the time')
      }
      const getTime = () => {
        let time = _self.timestampDateData.toString().replace(/00:00/, _self.timestampTimeData.toString())
        let localTime = moment(time).tz(moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss')
        let userTime = moment.tz(localTime, _self.itemInfo.timezone).format()
        let lastTime = moment(userTime).utc().format()
        // }
        return lastTime
      }
      const params = {
        comments: this.comments,
        logTimeUpdated: getTime(),
        tenantAttendanceId: this.itemInfo.id,
        userId: thisStore.state.user.id
      }
      this.$interface.attendance.updateTimeEntryApi(params)
        .then(({ data: res }) => {
          this.loadingSaveBtn = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
          this.closeDialog()
          // this.$parent.getUserChangeRecord()
          this.$emit('initOther')
        })
        .catch(() => {
          this.loadingSaveBtn = false
        })
    },
    openDialog () {
      this.editTimeEntryDialog = true
    },
    closeDialog () {
      this.editTimeEntryDialog = false
      // Object.assign(this.$data, this.$options.data())
    },
    closeAfterDialog () {
      Object.assign(this.$data, this.$options.data())
    },
    $t (key) {
      return i18n.t(key)
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding-bottom: 0 !important;
}
</style>
